package com.ailk.aee.pcc.mongo;

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 对 mongodb 的包装
 *
 * @author peng.zhang
 */
@SuppressWarnings("deprecation")
public class Mongo {

    private DB db;

    private String contentCollectionName;

    private int maxWaitTime = 1000 * 3;

    private int connectTimeout = 1000;

    private int socketTimeout = 3000;

    private int connectionsPerHost = 10;

    private int connectionMultiplier = 5;

    public void setContentCollectionName(String contentCollectionName) {
        this.contentCollectionName = contentCollectionName;
    }

    public void setMaxWaitTime(int maxWaitTime) {
        this.maxWaitTime = maxWaitTime;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public void setConnectionsPerHost(int connectionsPerHost) {
        this.connectionsPerHost = connectionsPerHost;
    }

    public void setConnectionMultiplier(int connectionMultiplier) {
        this.connectionMultiplier = connectionMultiplier;
    }

    /**
     * 构造方法
     *
     * @param host 服务器名称
     * @param port 服务器地址
     * @param db   数据库名称
     * @throws java.net.UnknownHostException 如果无法解析服务器地址
     */
    public Mongo(String host, int port, String db) throws UnknownHostException {
        MongoClient client = new MongoClient(host, port);
        this.db = client.getDB(db);
    }

    public Mongo(String host, int port, String db, String username, String password) throws UnknownHostException {

        MongoClient client = new MongoClient(
                new ServerAddress(host, port),
                Arrays.asList(MongoCredential.createCredential(username, db, password.toCharArray())),
                options()
        );

        this.db = client.getDB(db);
    }

    public Mongo(String addrs, String db) throws UnknownHostException {

        //切分地址
        List<ServerAddress> seeds = parseAddress(addrs);

        MongoClient client = new MongoClient(
                seeds, options()
        );

        //设置 secondary 读优先
        client.setReadPreference(ReadPreference.secondaryPreferred());

        this.db = client.getDB(db);
    }

    public Mongo(String addrs, String db, String username, String password) throws UnknownHostException {

        //解析地址
        List<ServerAddress> seeds = parseAddress(addrs);

        MongoClient client = new MongoClient(
                seeds,
                Arrays.asList(MongoCredential.createCredential(username, db, password.toCharArray())),
                options()
        );

        //设置 secondary 读优先
        client.setReadPreference(ReadPreference.secondaryPreferred());

        this.db = client.getDB(db);
    }

    // 获取指定的集合
    public DBCollection getContentCollection() {
        return this.db.getCollection(contentCollectionName);
    }

    public DBCollection getCollection(String collectionName) {
        return this.db.getCollection(collectionName);
    }

    // SECTION: inner helper

    // 设置连接参数
    private MongoClientOptions options() {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.maxWaitTime(maxWaitTime);
        builder.connectTimeout(connectTimeout);
        builder.socketTimeout(socketTimeout);
        builder.connectionsPerHost(connectionsPerHost);
        builder.threadsAllowedToBlockForConnectionMultiplier(connectionMultiplier);
        return builder.build();
    }

    // 解析地址
    private List<ServerAddress> parseAddress(String addrs) throws UnknownHostException {

        List<ServerAddress> seeds = new ArrayList<ServerAddress>();

        String[] servers = addrs.split(";");

        for (String server : servers) {
            String[] config = server.split(":");
            seeds.add(new ServerAddress(config[0], Integer.parseInt(config[1])));
        }

        return seeds;
    }


}
